package reflectionAndDynamic;
import java.awt.Color;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;

public class Color_name_string {
	public static String nameThisColor(Color color) throws Exception {

		//
		Class<?> enumClazz = Class.forName("java.awt.Color");
		for (Enum<?> e : ((Class<? extends Enum<?>>) enumClazz).getEnumConstants()) {
			System.out.println(e.name()); // The variable "e" would be
											// Enum2.ONE, etc
		}

		return "NO_MATCH";
	}

	public static void main(String[] args) throws Exception {
		// nameThisColor(null);
		getNameReflection(Color.red);
		Color redcolor = getColor("RED");
	}

	public static Color getColor(String colorName) {
		try {
			// Find the field and value of colorName
			Field field = Class.forName("java.awt.Color").getField(colorName);
			return (Color) field.get(null);
		} catch (Exception e) {
			return null;
		}
	}

	public static String getNameByComparision(Color color) {
		if (color.equals(Color.RED)) {
			return "RED";
		}
		if (color.equals(Color.BLACK)) {
			return "BLACK";
		}
		// ..
		return "NOT_DEFINED";
	}

	public static String getName(Color color) throws Exception, ClassNotFoundException {
		Field[] field = Class.forName("java.awt.Color").getDeclaredFields();

		for (Field fname : field) {
			// System.out.println(fname);
			String[] splSpace = fname.toString().split(" ");
			String lastStr = splSpace[splSpace.length - 1];
			String colorName = "";
			System.out.println(fname.getName());
			if (lastStr.startsWith("java.awt.Color.")) {
				String[] splLastDot = lastStr.split("\\.");
				colorName = splLastDot[splLastDot.length - 1];
			}
			Class c = Class.forName("java.awt.Color");

		}
		return null;
	}

	public static String getNameReflection(Color color) {
		try {
			Field[] field = Class.forName("java.awt.Color").getDeclaredFields();
			for (Field f : field) {
				String colorName = "";
				Class<?> t = f.getType();
				// System.out.println(f.getType());
				if (t == java.awt.Color.class) {
					colorName = f.getName();
					Color dec = (Color) f.get(null);
					if (dec.equals(color)) {
						System.out.println(colorName);
						return colorName.toUpperCase();
					}
				}
			}
		} catch (Exception e) {
			System.out.println("Exception... " + e.toString());
		}
		return "NO_MATCH";
	}
}
